<?php
/**
 * Created by PhpStorm.
 * User: luiz
 * Date: 2019/6/12
 * Time: 19:45
 */

namespace app\api\service;
use \app\api\modle\Order as OrderM;
use app\api\modle\Product;
use app\lib\enum\OrderStatusEnum;
use think\Db;
use think\Exception;
use think\Log;
use traits\think\Instance;

Loader::import('WxPay',EXTEND_PATH,'.Api.php');
class WxNotify extends \WxPayNotify
{
    public function NotifyProcess($data, &$msg)
    {

        if($data['result_code'] == 'SUCCESS')
        {
            $orderNo = $data['out_trade_no'];
            Db::startTrans();
            try{
                $order = OrderM::where('order_no','=',$orderNo)->find();
                if($order->status == 1)
                {
                    $service = new Order();
                    $stock_status = $service->checkOrderStock($order->id);
                    if($stock_status['pass'])
                    {
                        $this->updateOrderStatus($order->id,true);
                        $this->reduceStock($stock_status);
                    }
                    else
                        {
                            $this->updateOrderStatus($order->id,false);
                        }
                }
                Db::commit();
                return true;
            }
            catch (Exception $exception)
            {
                Db::rollback();
                Log::record($exception);
                return false;
            }
        }
        else
            {
                return true;
            }
        //return parent::NotifyProcess($data, $msg); // TODO: Change the autogenerated stub
    }
    private  function updateOrderStatus($orderID,$success)
    {
            $status = $success?OrderStatusEnum::PAID:OrderStatusEnum::PAID_BUT_OUT_OF;
            \app\api\modle\Order::where('id','=',$orderID)->update(['status'=>$status]);
    }
    private function reduceStock($stock_status)
    {
         foreach ($stock_status['pStatusArray'] as $singlePStatus)
         {
          //  $singlePStatus['count']
             Product::where('id','=',$singlePStatus['id'])->setDec('stock',$singlePStatus['count']);
         }
    }
}